<template>
    <div class="my-info-container">
        <div class="user-info-container">
            <div class="info">
                <el-form ref="form" :model="form" :rules="rules" label-width="120px">

                    <el-form-item label="用户姓名：" prop="realName">
                        <el-input v-model="form.realName" style="width: 306px;"></el-input>
                    </el-form-item>

                    <el-form-item label="邮箱地址：" prop="email">
                        <el-input v-model="form.email" style="width: 306px;"></el-input>
                    </el-form-item>

                    <el-form-item label="手机号码：" prop="mobile">
                        <el-input v-model="form.mobile" style="width: 306px;"></el-input>
                    </el-form-item>

                    <el-form-item label="登录账号：">
                        <el-input v-model="user.account" disabled style="width: 306px;"></el-input>
                    </el-form-item>

                    <el-form-item label="登录密码：">
                        <el-button type="text" @click="dialogEditPassVisible = true">修改密码</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-upload
                class="avatar-uploader"
                :action="UPLOAD_URL"
                :data="data"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </div>
        <div class="user-info-bto">
            <el-button>取消</el-button>
            <el-button type="primary" @click="updateInfo">保存</el-button>
        </div>

        <el-dialog title="修改密码" :visible.sync="dialogEditPassVisible" :close-on-press-escape="false" :close-on-click-modal="false"  @close="resetEditPasswordForm">
            <el-form :model="editPasswordForm" :rules="editPasswordRules" ref="editPasswordForm" labelPosition="right" labelWidth="100px" style="width: 400px">
                <el-form-item label="原密码" prop="oldPassword">
                    <el-input v-model="editPasswordForm.oldPassword"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="editPasswordForm.newPassword"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="rePass">
                    <el-input v-model="editPasswordForm.rePass"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditPassVisible = false">取 消</el-button>
                <el-button type="primary" @click="updatePassword">确 定</el-button>
            </div>
        </el-dialog>

    </div>

</template>

<script>
    import FileUpload from 'vue-upload-component'
    import ImageCompressor from 'image-compressor'
    import { mapGetters } from 'vuex'
    import { updatedMyInfo, updateMyPassword, updateMyAvatar, UPLOAD_URL } from '@/api/system/user'
    import { getToken } from "@/libs/auth";
    import uAvatar from '@/assets/images/avatar/avatar1.jpeg'
    export default {
        name: "my-info",
        components: {
            FileUpload
        },
        computed: {
            ...mapGetters(['user', 'roles', 'page_permissions', 'action_permissions'])
        },
        created() {

            this.form.id = this.user.id
            this.form.realName = this.user.realName
            this.form.email = this.user.email
            this.form.mobile = this.user.mobile
            this.form.avatar = this.user.avatar
            this.editPasswordForm.id = this.user.id

            if(this.form.avatar) {
                this.imageUrl = this.form.avatar
            } else {
                this.imageUrl = uAvatar
            }
        },
        mounted: function () {
            this.$nextTick(function () {
            })
        },
        data() {
            const validPhone = (rule, value, callback) => {
                var re = /^1[0-9]{10}$/;
                if (!re.test(value)) {
                    callback(new Error('请输入正确格式的手机号'));
                } else {
                    callback();
                }
            }
            const validRePassword = (rule, value, callback) => {
                if (value !== this.editPasswordForm.newPassword) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            }
            return {
                imageUrl: '',
                UPLOAD_URL,
                data: {
                    ossNam: 'qiniuyun',
                    bucketName: 'test',
                    prefixName: 'avatar'
                },
                form: {},
                rules: {
                    realName: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '邮件地址不能为空', trigger: 'blur' },
                        { type: 'email', message: '邮件格式不正确', trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请输入手机号码' },
                        { validator: validPhone }
                    ]
                },
                editPasswordRules: {
                    oldPassword: [
                        { required: true, message: '请输入原密码', trigger: 'blur' }
                    ],
                    newPassword: [
                        { required: true, message: '请输入新密码', trigger: 'blur' },
                        { min: 6, message: '请至少输入6个字符', trigger: 'blur' },
                        { max: 32, message: '最多输入32个字符', trigger: 'blur' }
                    ],
                    rePass: [
                        { required: true, message: '请再次输入新密码', trigger: 'blur' },
                        { validator: validRePassword, trigger: 'blur' }
                    ]
                },

                dialogEditPassVisible: false, // 修改密码Dialog
                editPasswordForm: {
                    oldPassword: '',
                    newPassword: '',
                    rePass: ''
                }
            }
        },
        methods: {
            handleAvatarSuccess(res, file) {
                this.form.avatar = file.response.data.url
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                /* const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M; */
            },
            updateInfo() {  //修改信息
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        let self = this
                        updatedMyInfo(this.form).then(response => {
                            if (response.data.status === 200) {
                                this.$store.dispatch('FedLogOut').then(() => {
                                    this.$alert('修改成功，请重新登录', '提示', {
                                        confirmButtonText: '重新登陆',
                                        callback: () => {
                                            this.$loading({
                                                lock: true,
                                                text: '正在退出，请稍等...',
                                                background: 'rgba(0, 0, 0, 0.7)'
                                            });
                                            setTimeout(()=>{
                                                window.location.reload()
                                            }, 500)

                                        }
                                    })
                                })
                            } else if(response.data.status === 601) {
                                this.$notify({
                                    title: '提示', message: response.data.msg,
                                    type: 'warning', duration: 2000
                                })
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.msg,
                                    type: 'error', duration: 2000
                                })
                            }
                        }).catch(error => {})
                    }
                })
            },
            updatePassword() { //修改密码
                this.$refs['editPasswordForm'].validate((valid) => {
                    if (valid) {
                        updateMyPassword(this.editPasswordForm).then(response => {
                            if (response.data.status === 200) {
                                this.dialogEditPassVisible = false
                                this.$notify({
                                    title: '提示', message: '操作成功',
                                    type: 'success', duration: 2000
                                })
                            } else if(response.data.status === 601) {
                                this.$notify({
                                    title: '提示', message: response.data.msg,
                                    type: 'warning', duration: 2000
                                })
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.msg,
                                    type: 'error', duration: 2000
                                })
                            }
                        }).catch(error => {})
                    }
                })
            },
            
            resetEditPasswordForm() {
                this.$refs['editPasswordForm'].resetFields()
                this.editPasswordForm = {
                    id:this.user.id,
                    oldPassword: '',
                    newPassword: '',
                    rePass: ''
                }
            },

        }
    }
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    height: 150px;
    width: 150px;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 100%;
    height: 100%;
    display: block;
}
</style>
<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>
    .my-info-container{
        .user-info-container{
            display: flex;
            flex-direction: row;
            .info{
                margin-right: 100px;
            }
        }
        .user-info-bto{
            margin-left: 35px;
        }
    }
</style>
